package com.ruoyi.parking.service.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.parking.mapper.ParkingAppointmentMapper;
import com.ruoyi.parking.mapper.ParkingLotMapper;
import com.ruoyi.parking.mapper.ParkingSpaceMapper;
import com.ruoyi.parking.domain.ParkingAppointment;
import com.ruoyi.parking.domain.ParkingLot;
import com.ruoyi.parking.domain.ParkingSpace;
import com.ruoyi.parking.service.IParkingAppointmentService;

/**
 * 停车预约Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@Service
public class ParkingAppointmentServiceImpl implements IParkingAppointmentService 
{
    @Autowired
    private ParkingAppointmentMapper parkingAppointmentMapper;

    @Autowired
    private ParkingLotMapper parkingLotMapper;

    @Autowired
    private ParkingSpaceMapper parkingSpaceMapper;

    /**
     * 查询停车预约
     * 
     * @param id 停车预约主键
     * @return 停车预约
     */
    @Override
    public ParkingAppointment selectParkingAppointmentById(Long id)
    {
        return parkingAppointmentMapper.selectParkingAppointmentById(id);
    }

    /**
     * 查询停车预约列表
     * 
     * @param parkingAppointment 停车预约
     * @return 停车预约
     */
    @Override
    public List<ParkingAppointment> selectParkingAppointmentList(ParkingAppointment parkingAppointment)
    {
        return parkingAppointmentMapper.selectParkingAppointmentList(parkingAppointment);
    }

    /**
     * 新增停车预约
     * 
     * @param parkingAppointment 停车预约
     * @return 结果
     */
    @Override
    @Transactional
    public int insertParkingAppointment(ParkingAppointment parkingAppointment)
    {
        // 1. 校验预约时间不能是过去的日期
        Date now = DateUtils.getNowDate();
        if (parkingAppointment.getAppointTime().before(new Date(now.getTime() - 24 * 60 * 60 * 1000))) {
            throw new ServiceException("预约时间不能是过去的日期");
        }

        // 2. 校验停车场是否存在
        ParkingLot lot = parkingLotMapper.selectParkingLotById(parkingAppointment.getLotId());
        if (lot == null)
        {
            throw new ServiceException("停车场不存在");
        }

        // 3. 校验车位是否存在且属于该停车场
        ParkingSpace space = parkingSpaceMapper.selectParkingSpaceById(parkingAppointment.getSpaceId());
        if (space == null)
        {
            throw new ServiceException("车位不存在");
        }
        if (!space.getLotId().equals(parkingAppointment.getLotId()))
        {
            throw new ServiceException("车位不属于该停车场");
        }

        // 4. 校验车位状态是否可用
        if (!"0".equals(space.getCurrentStatus()))
        {
            throw new ServiceException("车位已被占用或预约，无法预约");
        }

        // 5. 检查该车位该时间是否已有预约
        int conflictCount = parkingAppointmentMapper.checkAppointmentConflict(
            parkingAppointment.getSpaceId(), 
            parkingAppointment.getAppointTime(), 
            null
        );
        if (conflictCount > 0)
        {
            throw new ServiceException("该车位该时间已被预约");
        }

        // 6. 创建预约
        parkingAppointment.setStatus("0"); // 待使用
        parkingAppointment.setCreateBy(SecurityUtils.getUsername());
        parkingAppointment.setCreateTime(DateUtils.getNowDate());
        int result = parkingAppointmentMapper.insertParkingAppointment(parkingAppointment);

        // 7. 更新车位状态为已预约
        if (result > 0)
        {
            space.setCurrentStatus("2"); // 已预约
            space.setUpdateBy(SecurityUtils.getUsername());
            space.setUpdateTime(DateUtils.getNowDate());
            parkingSpaceMapper.updateParkingSpace(space);
        }

        return result;
    }

    /**
     * 修改停车预约
     * 
     * @param parkingAppointment 停车预约
     * @return 结果
     */
    @Override
    public int updateParkingAppointment(ParkingAppointment parkingAppointment)
    {
        return parkingAppointmentMapper.updateParkingAppointment(parkingAppointment);
    }

    /**
     * 批量删除停车预约
     * 
     * @param ids 需要删除的停车预约主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteParkingAppointmentByIds(Long[] ids)
    {
        // 取消预约时释放车位
        for (Long id : ids) {
            releaseSpaceByAppointment(id);
        }
        return parkingAppointmentMapper.deleteParkingAppointmentByIds(ids);
    }

    /**
     * 删除停车预约信息
     * 
     * @param id 停车预约主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteParkingAppointmentById(Long id)
    {
        // 取消预约时释放车位
        releaseSpaceByAppointment(id);
        return parkingAppointmentMapper.deleteParkingAppointmentById(id);
    }

    /**
     * 释放车位（取消预约时调用）
     * 
     * @param appointmentId 预约ID
     */
    private void releaseSpaceByAppointment(Long appointmentId)
    {
        ParkingAppointment appointment = parkingAppointmentMapper.selectParkingAppointmentById(appointmentId);
        if (appointment != null && appointment.getSpaceId() != null)
        {
            ParkingSpace space = parkingSpaceMapper.selectParkingSpaceById(appointment.getSpaceId());
            if (space != null && "2".equals(space.getCurrentStatus()))
            {
                // 只有当车位状态为已预约时，才释放为空闲
                space.setCurrentStatus("0");
                space.setUpdateBy(SecurityUtils.getUsername());
                space.setUpdateTime(DateUtils.getNowDate());
                parkingSpaceMapper.updateParkingSpace(space);
            }
        }
    }
}
